package controller.alarm;

import java.util.Calendar;
import java.util.Vector;

import layout.alarm.CustomDialogSelectDay;
import object.alarm.Alarm;
import utility.alarm.GUI_Ulti;
import utility.alarm.SettingAlarm;
import utility.alarm.StringUlti;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TimePicker;

public class AddAlarm extends Activity implements OnClickListener, OnCheckedChangeListener {

	private static final int TIME_DIALOG_ID = 0;
	private static final int DATE_DIALOG_ID = 1;

	private static boolean flagRepeat = true;
	private int hourEdit = 0;
	private int minuteEdit = 0;
	private String am_pm;
	private int eDayOfWeek = 0;
	private int eDayOfMonth = 0;
	private int eMonth = -1;
	private int eYear = 0;
	public static Vector<Integer> listDays;
	private static String formatTime = "";
	private static String formatDD = "";
	public static String[] fileAudio = new String[2];
	public static String work = "";

	private static EditText etSelectTime;
	private static EditText etSelectDD;
	private static EditText etWork;
	private static EditText etAudio;
	private RadioGroup rdGroupRepeat;
	private RadioButton rdbtnDisable;
	private Button btnAdd;
	private Button btnCancel;

	private Intent intent;

	private static StringUlti strUlti = StringUlti.getInstance();
	private Alarm alarm;
	private Calendar c;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_alarm);
		etSelectTime = (EditText) findViewById(R.id.selectTime);
		etSelectTime.setKeyListener(null);
		etSelectTime.setOnClickListener(this);
		c = Calendar.getInstance();
		hourEdit = c.get(Calendar.HOUR_OF_DAY);
		minuteEdit = c.get(Calendar.MINUTE);
		am_pm = strUlti.getAM_PM(c.get(Calendar.AM_PM));
		if(formatTime.equals("")){			
			formatTime = strUlti.formatTime(strUlti.formatHour(hourEdit), minuteEdit, am_pm);
		}
		GUI_Ulti.getInstance().updateEditTxt(etSelectTime, formatTime);
		
		rdGroupRepeat = (RadioGroup) findViewById(R.id.radioGroupRepeat);
		rdGroupRepeat.setOnCheckedChangeListener(this);
		if(flagRepeat){
			((RadioButton)rdGroupRepeat.getChildAt(0)).setChecked(true);
		}else ((RadioButton)rdGroupRepeat.getChildAt(1)).setChecked(true);
		
		etSelectDD = (EditText) findViewById(R.id.selectDD);
		etSelectDD.setKeyListener(null);
		etSelectDD.setOnClickListener(this);
		if(formatDD.equals("")){
			formatDD = strUlti.formatDayOfWeek(c.get(Calendar.DAY_OF_WEEK));
			listDays = new Vector<Integer>();
			listDays.add(c.get(Calendar.DAY_OF_WEEK));
		}
		GUI_Ulti.getInstance().updateEditTxt(etSelectDD, formatDD);
		
		etWork = (EditText) findViewById(R.id.work);
		GUI_Ulti.getInstance().updateEditTxt(etWork, work);
		
		etAudio = (EditText) findViewById(R.id.audio);
		etAudio.setKeyListener(null);
		etAudio.setOnClickListener(this);
		if(fileAudio.length>0) GUI_Ulti.getInstance().updateEditTxt(etAudio, fileAudio[0]);
		
		rdbtnDisable = (RadioButton) findViewById(R.id.rdbtnDisable);
		rdbtnDisable.setEnabled(false);
		
		btnAdd = (Button) findViewById(R.id.btnAdd1);
		btnAdd.setOnClickListener(this);

		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(this);
	}

	private void repeat() {
		flagRepeat = true;
		c = Calendar.getInstance();
		etSelectDD = (EditText) findViewById(R.id.selectDD);
		etSelectDD.setKeyListener(null);
		etSelectDD.setOnClickListener(this);
		if (listDays == null) {
			listDays = new Vector<Integer>();
			listDays.add(c.get(Calendar.DAY_OF_WEEK));
			formatDD = strUlti.formatDayOfWeek(c.get(Calendar.DAY_OF_WEEK));
		}else{
			formatDD = strUlti.getListDays(listDays);
		}
		GUI_Ulti.getInstance().updateEditTxt(etSelectDD, formatDD);
	}

	private void onceTime() {
		flagRepeat = false;
		c = Calendar.getInstance();
		etSelectDD = (EditText) findViewById(R.id.selectDD);
		etSelectDD.setKeyListener(null);
		etSelectDD.setOnClickListener(this);
		eDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		eDayOfMonth = c.get(Calendar.DAY_OF_MONTH);
		eMonth = c.get(Calendar.MONTH);
		eYear = c.get(Calendar.YEAR);
		String dateEdit = strUlti.formatDate(eDayOfWeek, eDayOfMonth, eMonth, eYear);
		GUI_Ulti.getInstance().updateEditTxt(etSelectDD, dateEdit);
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case TIME_DIALOG_ID:
				return new TimePickerDialog(this, mTimeSetListener, hourEdit, minuteEdit, false);
			case DATE_DIALOG_ID:
				return new DatePickerDialog(this, mDateSetListener, eYear, eMonth, eDayOfMonth);
		}
		return null;
	}

	private OnTimeSetListener mTimeSetListener = new OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			hourEdit = hourOfDay;
			minuteEdit = minute;
			int hour = strUlti.formatHour(hourEdit);
			if (hour != hourEdit){
				am_pm = "PM";
			}else{
				am_pm = "AM";
			}				
			formatTime = strUlti.formatTime(hour, minuteEdit, am_pm);
			GUI_Ulti.getInstance().updateEditTxt(etSelectTime, formatTime);
		}
	};
	
	private OnDateSetListener mDateSetListener = new OnDateSetListener() {
		
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			eYear = year;
			eMonth = monthOfYear;
			eDayOfMonth = dayOfMonth;
			Calendar cal = Calendar.getInstance();
			cal.set(eYear, eMonth, eDayOfMonth);
			eDayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
			formatDD = strUlti.formatDate(eDayOfWeek, eDayOfMonth, eMonth, eYear);
			GUI_Ulti.getInstance().updateEditTxt(etSelectDD, formatDD);
		}
	};

	public static void getListDays(Vector<Integer> list) {
		listDays = list;
		formatDD = strUlti.getListDays(listDays);
		GUI_Ulti.getInstance().updateEditTxt(etSelectDD, formatDD);
	}

	public void onClick(View v) {
		if (v == etSelectTime) {
			showDialog(TIME_DIALOG_ID);
		} else if (v == etSelectDD) {
			if(flagRepeat){
				CustomDialogSelectDay cstd = new CustomDialogSelectDay(this);
				cstd.show();
			}else{
				showDialog(DATE_DIALOG_ID);
			}
		} else if (v == etAudio){
			work = etWork.getText().toString();
			Intent intentAudio = new Intent(AddAlarm.this.getApplicationContext(), MusicListActivity.class);
			AddAlarm.this.startActivity(intentAudio);
		} else if (v == btnAdd) {
			if (etSelectDD.getText() != null || !etSelectDD.getText().toString().equals("")) {
				alarm = new Alarm();
				alarm.setTime(formatTime);
				if(flagRepeat) alarm.setDay(formatDD);
				else alarm.setDate(formatDD);
				alarm.setType(flagRepeat);
				alarm.setStatus(true);
				work = etWork.getText().toString();
				alarm.setWork(work);
				if(!fileAudio[0].equals(null) || !fileAudio[0].equals("")) alarm.setAudio(fileAudio[1]);
				else alarm.setAudio("");
				alarm.setId((int) AlarmActivity.dataSource.addAlarm(alarm));
				
				if(flagRepeat){
					for (int i = 0; i < listDays.size(); i++) {
						Calendar calendar = Calendar.getInstance();
						calendar.set(Calendar.DAY_OF_WEEK, listDays.get(i));
						calendar.set(Calendar.HOUR_OF_DAY, hourEdit);
						calendar.set(Calendar.MINUTE, minuteEdit);
						calendar.set(Calendar.SECOND, 0);
						calendar.set(Calendar.MILLISECOND, 0);
						
						Bundle sendBundle = new Bundle();
						sendBundle.putInt(SettingAlarm.send_receive, alarm.getId());
						intent = new Intent(this.getApplicationContext(), AlarmReceiver.class);
						intent.putExtras(sendBundle);
						PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), alarm.getId(), intent, alarm.getId());
						AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
						alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
														SettingAlarm.Default_Repeat_Alarm, pendingIntent);
						AlarmActivity.listPI.put(alarm.getId(), pendingIntent);
						AlarmActivity.listAlarmManager.put(alarm.getId(), alarmManager);
					}
				}else{
					Calendar calendar = Calendar.getInstance();
					calendar.set(Calendar.YEAR, eYear);
					calendar.set(Calendar.MONTH, eMonth);
					calendar.set(Calendar.DAY_OF_MONTH, eDayOfMonth);
					calendar.set(Calendar.HOUR_OF_DAY, hourEdit);
					calendar.set(Calendar.MINUTE, minuteEdit);
					calendar.set(Calendar.SECOND, 0);
					calendar.set(Calendar.MILLISECOND, 0);
					
					Bundle sendBundle = new Bundle();
					sendBundle.putInt(SettingAlarm.send_receive, alarm.getId());
					intent = new Intent(this.getApplicationContext(), AlarmReceiver.class);
					intent.putExtras(sendBundle);
					PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), alarm.getId(), intent, alarm.getId());
					AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
					alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
													SettingAlarm.Default_Repeat_Alarm, pendingIntent);
					AlarmActivity.listPI.put(alarm.getId(), pendingIntent);
					AlarmActivity.listAlarmManager.put(alarm.getId(), alarmManager);
				}
				
			} else return;

			Intent intentReturnMain = new Intent(AddAlarm.this,	AlarmActivity.class);
			AddAlarm.this.startActivity(intentReturnMain);
			AddAlarm.this.finish();
		} else if (v == btnCancel) {
			Intent intent = new Intent(AddAlarm.this, AlarmActivity.class);
			AddAlarm.this.startActivity(intent);
			AddAlarm.this.finish();
		}

	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		if(group == rdGroupRepeat){
			int checkedRadioButton = group.getCheckedRadioButtonId();
			switch (checkedRadioButton) {
				case R.id.rdbtnRepeat:
					repeat();
					break;
				case R.id.rdbtnOnceTime:
					onceTime();
					break;
			}
		}
	}

}
